﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;


namespace DATN.Account
{
    public partial class Registration : System.Web.UI.Page
    {
        SqlConnection cnn;
        SqlCommand cmd;

        protected void Page_Load(object sender, EventArgs e)
        {
          
        }

        int ChUs;
        //Check UserName: Kiem tra UserName có hay ko
        protected int check_User(string username)
        {
            ChUs = 0;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Count(*) FROM Users WHERE UserName=@username";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@username", SqlDbType.VarChar);
                cmd.Parameters["@username"].Value = username;

                ChUs = Convert.ToInt32(cmd.ExecuteScalar().ToString());
            }
            catch (Exception ex)
            {
                Response.Write(" Lỗi ở Check UserName: " + ex);
            }
            return ChUs;
        }

        int us_id;
        //Nhập userName vào trả Id
        protected int UserName_Info(string username)
        {
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Us_Id FROM Users WHERE UserName=@username";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@username", SqlDbType.VarChar);
                cmd.Parameters["@username"].Value = username;

                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    us_id = Convert.ToInt16(reader["Us_Id"].ToString());
                    //InsertRole(us_id);
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write(" Lỗi ở Check UserName: " + ex);
            }
            return us_id;
        }

        int ChMail;
        //check mail ton tai:
        protected int check_Mail(string mail)
        {
            ChMail = 0;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Count(*) FROM Users WHERE Mail=@mail";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@mail", SqlDbType.VarChar);
                cmd.Parameters["@mail"].Value = mail;

                ChMail = Convert.ToInt32(cmd.ExecuteScalar().ToString());
                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write(" Lỗi ở Check Mail: " + ex);
            }
            return ChMail;
        }

        //Dang ki:
        protected void Dangki(string UserName, string Password, string Mail, string FirstName, string LastName)
        {
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();
                cmd = cnn.CreateCommand();
                cmd.CommandText = "INSERT INTO Users (UserName, Password, Mail, FirstName, LastName) "
                                    + "VALUES (@UserName, @Password, @Mail, @FirstName, @LastName) ";

                cmd.Parameters.Add("@UserName", SqlDbType.NVarChar);
                cmd.Parameters["@UserName"].Value = UserName;

                cmd.Parameters.Add("@Password", SqlDbType.NVarChar);
                cmd.Parameters["@Password"].Value = Encrypt.EncryptText(Password, true);

                cmd.Parameters.Add("@Mail", SqlDbType.VarChar);
                cmd.Parameters["@Mail"].Value = Mail;

                cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar);
                cmd.Parameters["@FirstName"].Value = FirstName;

                cmd.Parameters.Add("@LastName", SqlDbType.NVarChar);
                cmd.Parameters["@LastName"].Value = LastName;

                cmd.ExecuteNonQuery();


                cmd.CommandText = "";
                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write(" Lỗi ở Đăng kí: "+ ex);
            }
            finally{
                cnn.Close();
            }
        }

        //InsertRole
        protected void InsertRole(int us_id)
        {
             try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();
                cmd = cnn.CreateCommand();
                cmd.CommandText = "Insert Into UserRole (Ro_Id, Us_Id)"
                                + " Values (2, @Us_Id)";

                cmd.Parameters.Add("@Us_Id", SqlDbType.NVarChar);
                cmd.Parameters["@Us_Id"].Value = us_id;

                cmd.ExecuteNonQuery();

                cmd.CommandText = "";
                cnn.Close();
            }
             catch (Exception ex)
             {
                 cnn.Close();
                 Response.Write(" Lỗi ở Đăng kí: " + ex);
             }
             finally
             {
                 cnn.Close();
             }
        }

        //Send Mail
        protected void SendMail()
        { 
         try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("midasfpt@gmail.com");
                mail.To.Add(tbx_Mail.Text);
                mail.Subject = "Chào Mừng đến Mindasvn.com";
                mail.Body = "Chào Mừng bạn đến với Mindasvn.com"
                                +". Bạn Vừa đăng kí tại Mindasvn tài khoản: " + tbx_UserName.Text
                                +". Đây là Mail tự động. Bạn không nên Reply lại mail này!";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("midasfpt@gmail.com", "midas123$%^"); //you have to provide you gmail username and password
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
 
            }
            catch (Exception ex)
            {
                Lb_Register.Text = "Địa chỉ mail ko đúng. Xin thử lại" ;
            }
        }
        
        //Click Dang ki
        protected void Submit_Click(object sender, EventArgs e)
        {
            if (check_User(tbx_UserName.Text) == 1)
            {
                Lb_Register.Text = "Tên tài khoản bạn chọn đã tồn tại. Vui lòng chọn tên khác.";
            }
            else
            {
                if (check_Mail(tbx_Mail.Text) == 1)
                {
                    Lb_Register.Text = "Địa Chỉ Mail này đã được sử dụng, Hãy thêm địa chỉ mail mới";
                }
                else
                {
                    SendMail();
                    Dangki(tbx_UserName.Text, tbx_Pass.Text, tbx_Mail.Text, tbx_FirstName.Text, tbx_LastName.Text);
                    InsertRole(UserName_Info(tbx_UserName.Text));
                    Response.Redirect("~/Account/Resuccess.aspx");
                    
                }
            }
        }

       
    }
}
